package quizman.mappers;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import quizman.domain.Choice;
import quizman.domain.Question;
import quizman.tdg.MultipleChoiceTDG;

/**
 * 
 */

/**
 * @author Team0i
 *
 */
public class MultipleChoiceMapper {
	public static List<Choice> find(String questionName) throws Exception {
		try {
			ResultSet rs = MultipleChoiceTDG.find(questionName);
			List<Choice> choiceList = new ArrayList<Choice>();
			if(!rs.next()) return null;
			do {
				boolean isRight = (rs.getString("isRight").contains("TRUE"));
				String text = rs.getString("Answer_Text");
				Choice c = new Choice(text, isRight);
				choiceList.add(c);
			} while(rs.next());
			return choiceList;
		} catch (Exception e) {
			String msg = "Error in MultipleChoice.find";
			throw new Exception(msg, e);
		}
	}
	
	public static void insert(Question q, List<Choice> choices) throws Exception {
		try {
			for(Choice c : choices) {
				MultipleChoiceTDG.insert(q.getName(), c.getText(), c.isCorrect());
			}
		} catch (Exception e) {
			String msg = "Error in MultipleChoice.insert";
			throw new Exception(msg,e);
		}
	}
	
	public static void update(Question q, List<Choice> choices, List<Choice> oldChoices) throws Exception {
		try {
			for(int i = 0; i < choices.size(); i++) {
				MultipleChoiceTDG.update(q.getName(), oldChoices.get(i).getText(), choices.get(i).getText(), choices.get(i).isCorrect());
			}
		} catch (Exception e) {
			String msg = "Error in MultipleChoice.update";
			throw new Exception(msg,e);
		}
	}
	
	public static void delete(Question q, List<Choice> choices) throws Exception {
		try {
			for(Choice c : choices) {
				MultipleChoiceTDG.delete(q.getName(), c.getText());
			}
		} catch (Exception e) {
			String msg = "Error in MultipleChoice.delete";
			throw new Exception(msg,e);
		}
	}
	
	public static void deleteAll(Question q) throws Exception {
		try {
			MultipleChoiceTDG.deleteAll(q.getName());
		} catch (Exception e) {
			String msg = "Error in MultipleChoice.deleteAll";
			throw new Exception(msg,e);
		}
	}
}
